package com.ruoyi.workorder.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.member.domain.MessageReceive;
import com.ruoyi.member.domain.MessageSend;
import com.ruoyi.member.mapper.MessageReceiveMapper;
import com.ruoyi.member.mapper.MessageSendMapper;
import com.ruoyi.workorder.domain.WorkordersContactImage;
import com.ruoyi.workorder.mapper.WorkordersContactImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.ruoyi.workorder.mapper.WorkOrderMapper;
import com.ruoyi.workorder.domain.WorkOrder;
import com.ruoyi.workorder.service.IWorkOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 工单Service业务层处理
 * 
 * @author renyuxin
 * @date 2024-05-28
 */
@Service
public class WorkOrderServiceImpl implements IWorkOrderService 
{
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private WorkordersContactImageMapper workordersContactImageMapper;

    @Autowired
    private MessageSendMapper messageSendMapper;

    @Autowired
    private MessageReceiveMapper messageReceiveMapper;


    /**
     * 查询工单
     * 
     * @param woId 工单主键
     * @return 工单
     */
    @Override
    public WorkOrder selectWorkOrderByWoId(Long woId)
    {
        return workOrderMapper.selectWorkOrderByWoId(woId);
    }

    /**
     * 查询工单列表
     * 
     * @param workOrder 工单
     * @return 工单
     */
    @Override
    public List<WorkOrder> selectWorkOrderList(WorkOrder workOrder)
    {
        return workOrderMapper.selectWorkOrderList(workOrder);
    }

    /**
     * 新增工单
     * 
     * @param workOrder 工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public int insertWorkOrder(WorkOrder workOrder)
    {   // 创建时间
        workOrder.setWoDate(new Date());
        // 工单状态
        workOrder.setWoStatus(1);
        // 创建人
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = user.getUserId();
        workOrder.setCreateId(userId);
        // 工单编号
        String todayDate= LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 获取今天的最大工单编号
        String maxWoNumberToday = findMaxWoNumberToday(todayDate);
        int nextCount;
        if (maxWoNumberToday == null) {
            // 如果今天还没有工单，则从0001开始
            nextCount = 1;
        } else {
            // 获取今天的最大工单编号的后四位
            String sequenceStr = maxWoNumberToday.substring(maxWoNumberToday.length() - 4);
            nextCount = Integer.parseInt(sequenceStr) + 1;
        }
        String prefix = "GD-" + todayDate + "-";
        String suffix = String.format("%04d", nextCount);
        workOrder.setWoNumber(prefix + suffix);
        int i = workOrderMapper.insertWorkOrder(workOrder);
        if(i>0){
            // 工单 图片上传
            if(workOrder.getImages()!=null){
                addImgUrl(workOrder);
            }
            //发消息
            MessageSend messageSend = new MessageSend();
            messageSend.setUserId(userId);
            messageSend.setMessageContent(workOrder.getWoContent());
            messageSend.setProjectId(workOrder.getProjectId());
            messageSend.setMessageDate(new Date());
            int ms = messageSendMapper.insertMessageSend(messageSend);
            if(ms>0){
                List<Long> ids = new ArrayList<>();
                ids.add(workOrder.getResponsibleId());
                ids.add(workOrder.getHelpId());
                ids.add(workOrder.getReporterId());
                ids.add(workOrder.getCopyId());
                ids.forEach(id->{
                    if(id!=null){
                        MessageReceive messageReceive = new MessageReceive();
                        messageReceive.setMessageMyStatus(1);
                        messageReceive.setProjectId(workOrder.getProjectId());
                        messageReceive.setMessageId(messageSend.getMessageId());
                        messageReceive.setUserId(id);
                        messageReceiveMapper.insertMessageReceive(messageReceive);
                    }
                });
            }
        }
        return i;
    }

    private String findMaxWoNumberToday(String todayDate) {
        return workOrderMapper.findMaxWoNumberToday(todayDate);
    }


    /**
     * 修改工单
     * 
     * @param workOrder 工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public int updateWorkOrder(WorkOrder workOrder)
    {
        // 创建人
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = user.getUserId();
        workOrder.setCreateId(userId);

        int i = workOrderMapper.updateWorkOrder(workOrder);
        if(i>0){
            //数据库中图片
            String db = workOrderMapper.selectWorkOrderByWoId(workOrder.getWoId()).getImages();
            // 前台传过来的图片
            String front = workOrder.getImages();
            //做差
            List<String> list = getDiff(db,front);

            for(String url:list){
                String picUrl = url.substring(url.indexOf("/",1));
                File file = new File(RuoYiConfig.getProfile()+picUrl);
                if(file.exists()){
                    file.delete();
                }
            }
            workordersContactImageMapper.deleteByWoId(workOrder.getWoId());
            // 工单 图片上传
            addImgUrl(workOrder);
            // 发送通知消息
            MessageSend messageSend = new MessageSend();
            messageSend.setUserId(userId);
            messageSend.setMessageContent(workOrder.getWoContent());
            messageSend.setProjectId(workOrder.getProjectId());
            messageSend.setMessageDate(new Date());
            int ms = messageSendMapper.insertMessageSend(messageSend);
            if(ms>0){
                List<Long> ids = new ArrayList<>();
                ids.add(workOrder.getResponsibleId());
                ids.add(workOrder.getHelpId());
                ids.add(workOrder.getReporterId());
                ids.add(workOrder.getCopyId());
                ids.forEach(id->{
                    if(id!=null){
                        MessageReceive messageReceive = new MessageReceive();
                        messageReceive.setMessageMyStatus(1);
                        messageReceive.setProjectId(workOrder.getProjectId());
                        messageReceive.setMessageId(messageSend.getMessageId());
                        messageReceive.setUserId(id);
                        messageReceiveMapper.insertMessageReceive(messageReceive);
                    }
                });
            }
        }
        return i;
    }

    private List<String> getDiff(String db, String front) {
        //差集
        List<String> resultUrl = new ArrayList<>();
        //如果dburls为空，则返回空
        if(!StringUtils.hasText(db)){
            return resultUrl;
        }
        //前端传递过来的图片地址为空 则返回dburls
        List<String> list1 =  Arrays.asList(db.split(","));
        if(!StringUtils.hasText(front)){
            return list1;
        }
        //差集
        List<String> list2 = Arrays.asList(front.split(","));
        resultUrl=new ArrayList<>(list1);
        resultUrl.removeAll(list2);
        return resultUrl;
    }

    /**
     * 图片数据存入从表的方法
     */
    private void addImgUrl(WorkOrder workOrder) {
        String[] splitStr = workOrder.getImages().split(",");
        for(String url:splitStr){
            WorkordersContactImage workordersContactImage = new WorkordersContactImage();
            workordersContactImage.setWoImageSrc(url);
            workordersContactImage.setWoId(workOrder.getWoId());
            workordersContactImage.setWoImageDate(new Date());
            workordersContactImageMapper.insertWorkordersContactImage(workordersContactImage);
        }
    }


    /**
     * 批量删除工单 用这个
     * 
     * @param woIds 需要删除的工单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public int deleteWorkOrderByWoIds(Long[] woIds)
    {
        //删除数据库中的图片
        if(woIds!=null){
            for(Long woId:woIds){
                //数据库中的图片地址
                String dburls = workOrderMapper.selectWorkOrderByWoId(woId).getImages();
                //删除图片
                if(dburls!=null){
                    String[] splitStr = dburls.split(",");
                    for(String picUrl:splitStr){
                        String url = picUrl.substring(picUrl.indexOf("/",1));
                        File file = new File(RuoYiConfig.getProfile()+url);
                        if(file.exists()){
                            file.delete();
                        }
                    }
                }
            }
        }
        // 连表删除数据
        workordersContactImageMapper.deleteWorkordersContactImageByWoIds(woIds);
        return workOrderMapper.deleteWorkOrderByWoIds(woIds);
    }

    /**
     * 删除工单信息
     * 
     * @param woId 工单主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderByWoId(Long woId)
    {
        return workOrderMapper.deleteWorkOrderByWoId(woId);
    }

    @Override
    public List<String> hasRelated(Long woCatalogId) {
        return workOrderMapper.hasRelated(woCatalogId);
    }

    @Override
    public List<WorkOrder> selectWorkOrderListForUser(WorkOrder workOrder, Long userId) {
        return workOrderMapper.selectWorkOrderListForUser(workOrder,userId);
    }

    @Override
    public boolean checkNameUnique(WorkOrder workOrder) {
        Long id = workOrderMapper.checkNameUnique(workOrder);
        return id!=null;
    }

    @Override
    public List<Map<String, Object>> listProblemStatistics(Long projectId) {
        return workOrderMapper.selectListProblemStatistics(projectId);
    }
}
